package com.tobestronger.shouxiespringframework.context.annotation;

import cn.hutool.core.util.StrUtil;
import com.tobestronger.shouxiespringframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor;
import com.tobestronger.shouxiespringframework.beans.factory.config.BeanDefinition;
import com.tobestronger.shouxiespringframework.beans.factory.support.BeanDefinitionRegistry;
import com.tobestronger.shouxiespringframework.stereotype.Component;

import java.util.Set;

/**
 * 扫描指定(多个)路径中符合要求的类 并注册到bean定义注册表中
 */
public class ClassPathBeanDefinitionScanner extends ClassPathScanningCandidateComponentProvider {

    private BeanDefinitionRegistry registry;

    public ClassPathBeanDefinitionScanner(BeanDefinitionRegistry registry) {
        this.registry = registry;
    }

    /**
     * 扫描 basePackages 里每个路径里 被Component注解的类 生成并注册BeanDefinition
     * @param basePackages
     */
    public void doScan(String... basePackages) {
        for (String basePackage : basePackages) {

            Set<BeanDefinition> candidates = findCandidateComponents(basePackage);

            for (BeanDefinition beanDefinition : candidates) {

                // 解析 Bean 的作用域 singleton、prototype
                String beanScope = resolveBeanScope(beanDefinition);
                if (StrUtil.isNotEmpty(beanScope)) {
                    beanDefinition.setScope(beanScope);
                }

                registry.registerBeanDefinition(determineBeanName(beanDefinition), beanDefinition);
            }
        }

        // 注册处理（@Autowired、@Value）注解的 AutowiredAnnotationBeanPostProcessor
        registry.registerBeanDefinition(
                "com.tobestronger.shouxiespringframework.context.annotation.internalAutowiredAnnotationProcessor",
                new BeanDefinition(AutowiredAnnotationBeanPostProcessor.class)
        );

    }

    /**
     * 解析 Scope注解 制定的bean的作用域
     *
     * @param beanDefinition
     * @return
     */
    private String resolveBeanScope(BeanDefinition beanDefinition) {
        Class<?> beanClass = beanDefinition.getBeanClass();
        Scope scope = beanClass.getAnnotation(Scope.class);
        if (null != scope) return scope.value();
        return StrUtil.EMPTY;
    }

    /**
     * 确定 bean定义注册表中 的beanName
     *
     * @param beanDefinition
     * @return
     */
    private String determineBeanName(BeanDefinition beanDefinition) {
        Class<?> beanClass = beanDefinition.getBeanClass();
        Component component = beanClass.getAnnotation(Component.class);
        String value = component.value();
        if (StrUtil.isEmpty(value)) {
            value = StrUtil.lowerFirst(beanClass.getSimpleName());
        }
        return value;
    }

}
